package com.hup.sidebar.androidService;

import android.accessibilityservice.AccessibilityService;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

import com.hup.sidebar.R;
import com.hup.sidebar.SideBarApplication;
import com.hup.sidebar.framework.util.PermissionUtil;
import com.hup.sidebar.framework.util.ToastUtil;
import com.hup.sidebar.model.AppConfig;

/**
 * 无障碍服务,
 * 启动服务说明:
 * .需要用户手动在系统设置中启动服务
 * .一旦用户启动服务,则设备重启后会自启动本服务,不需要 RECEIVE_BOOT_COMPLETED 权限
 *
 * @author hugan
 * @date 2022/6/7
 */
public class MyAccessibilityService extends AccessibilityService {
    private static final String TAG = MyAccessibilityService.class.getSimpleName();

    private AppConfig appConfig;

    @Override
    protected void onServiceConnected() {
        Log.i(TAG, "onServiceConnected: ");
        SideBarApplication.putBean(this);
        SideBarApplication.onAccessibilityStarted(true);
        appConfig = SideBarApplication.getBean(AppConfig.class);
        if (!appConfig.floaterStarted && appConfig.autoStart) {
            //启动悬浮窗
            if (PermissionUtil.hasOverlayPermission(this)) {
                AppService.switchService(true);
            } else {
                Log.i(TAG, "onServiceConnected: 无悬浮窗权限");
                //可能不显示,系统问题?
                ToastUtil.short_(getString(R.string.service_started));
            }
        } else {
            ToastUtil.short_(getString(R.string.service_started));
        }
    }

    /**
     * @deprecated 致命缺陷, 不能准确获取当前app;
     * 代码已不可达, 已去掉权限, android:accessibilityEventTypes="typeWindowStateChanged"
     */
    @Override
    public void onAccessibilityEvent(AccessibilityEvent e) {
        int type = e.getEventType();
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            //监听app切换,非常坑!!,详见isActivity注释

            //没配置白名单
            if (appConfig.whiteList.isEmpty()) return;
            AppService appService = SideBarApplication.getBeanNullable(AppService.class);
            //没启动服务
            if (appService == null) return;

            String currentApp = e.getPackageName().toString();
            boolean isActivity = isActivity(e, currentApp);
            if (!isActivity) return;
            Log.d(TAG, "onAccessibilityEvent: " + currentApp);

            //bug:可能是AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED
            boolean isWhite = appConfig.whiteList.contains(currentApp);
            if (isWhite) {
                if (appService.showingFloater()) appService.switchFloaterService(false);
            } else {
                if (!appService.showingFloater()) appService.switchFloaterService(true);
            }
        } else {
            //不会发生
            Log.i(TAG, "onAccessibilityEvent: 未知事件" + e);
        }
    }

    /**
     * 坑和笔记,详见[笔记.txt]
     *
     * @return false-过滤本app/其他app的悬浮窗事件
     */
    @SuppressWarnings("CommentedOutCode")
    private boolean isActivity(AccessibilityEvent e, String packageName) {
        String clz = e.getClassName().toString();
        /*
        try {
            //对[微信,微博]等无效!
            ComponentName componentName = new ComponentName(packageName, clz);
            ActivityInfo info = getPackageManager().getActivityInfo(componentName, 0);
        } catch (PackageManager.NameNotFoundException err) {
            Log.e(TAG, "tryGetActivity: " + err);
        }/**/

        /*
        本app的悬浮窗: com.hup.sidebar, android.widget.FrameLayout
        过渡动画?? 系统app, android.widget.FrameLayout
         */
        int changeTypes = e.getContentChangeTypes();
        Log.i(TAG, "isActivity: clz=" + packageName + ", " + clz + ", " + changeTypes);
        Log.i(TAG, "isActivity: " + getWindows());
        return !clz.endsWith("Layout");
    }

    @Override
    public void onInterrupt() {
        Log.i(TAG, "onInterrupt: ");
        SideBarApplication.removeBean(getClass());
        SideBarApplication.onAccessibilityStarted(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        SideBarApplication.removeBean(getClass());
        SideBarApplication.onAccessibilityStarted(false);
    }

    /**
     * 模拟按键
     *
     * @param action 如 {@link AccessibilityService#GLOBAL_ACTION_BACK}
     */
    public void fireKey(Integer action) {
        performGlobalAction(action);
    }

}
